package com.navinfo.platform.common.service.impl;

import com.navinfo.platform.common.service.ICommonService;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public enum CommonService implements ICommonService {
    INSTANCE;
    private static Map<String, String> config = new HashMap<>();

    @Override
    public void initConfig(String fileName, String[] args) {
        if(config.size() == 0){
            try {
                File directory = new File(CommonService.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile();
                Properties properties = new Properties();
                if(StringUtils.contains(fileName,",")){
                    String[] subFileNames=fileName.split(",");
                    for(String subName:subFileNames){
                        loadProps(subName, directory, properties);
                    }
                }else{
                    loadProps(fileName, directory, properties);
                }


                Enumeration<Object> keys = properties.keys();
                while(keys.hasMoreElements()){
                    Object key = keys.nextElement();
                    String value = properties.get(key).toString();
                    config.put(key.toString(), value);
                }

                if(args != null && args.length > 0){
                    for(int i = 0; i < args.length; i++){
                        config.put("args_" + (i + 1), args[i]);
                    }
                }
                //将YYYY-MM-DD 类型的日期格式转为 YYYYMMDD格式
                String dayValue= config.get(ICommonService.DAY_VALUE);;
                if(StringUtils.isNotEmpty(dayValue)&&StringUtils.contains(dayValue,"-")){
                    dayValue=dayValue.replace("-","");
                    config.put(ICommonService.DAY_VALUE,dayValue);
                }

            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
    }

    private void loadProps(String fileName, File directory, Properties properties) throws IOException {
        InputStream inputStream = new FileInputStream(directory.getAbsolutePath() + File.separator + fileName);
        properties.load(inputStream);
        inputStream.close();
    }

    @Override
    public Map<String, String> getConfig() {
        return config;
    }
}
